// 消息管理API接口
import type { Message, GetMessagesParams, MessageStats, BatchOperationRequest } from '../types/message';
import { http, getAPI_BASE_URL_SYNC } from '../lib/http-client';
import { shouldUseMockServer } from '../config/app.config';
import { messageData, getMessageStats } from '../data/messageData';

// 消息API基础路径
const MESSAGE_API_BASE = `${getAPI_BASE_URL_SYNC()}/messages`;

// API响应接口
export interface ApiResponse<T> {
  data: T;
  total: number;
  success: boolean;
  message?: string;
}

// 后端API响应格式（根据实际后端API调整）
interface BackendApiResponse<T> {
  code: number;
  message: string;
  data: T;
  total?: number;
  success?: boolean;
}

// 消息列表响应格式
interface MessageListResponse {
  messages: Message[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

// 消息统计响应格式
interface MessageStatsResponse {
  stats: MessageStats;
}

// 消息模拟API实现
const mockMessageApi = {
  async getMessages(params: GetMessagesParams = {}): Promise<ApiResponse<Message[]>> {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const { page = 1, pageSize = 10, type, read, important, search } = params;
    
    // 过滤数据
    let filteredData = [...messageData];
    
    if (type) {
      filteredData = filteredData.filter(message => message.type === type);
    }
    
    if (read !== undefined) {
      filteredData = filteredData.filter(message => message.read === read);
    }
    
    if (important !== undefined) {
      filteredData = filteredData.filter(message => message.important === important);
    }
    
    if (search) {
      filteredData = filteredData.filter(message => 
        message.title.toLowerCase().includes(search.toLowerCase()) ||
        message.content.toLowerCase().includes(search.toLowerCase()) ||
        message.sender?.toLowerCase().includes(search.toLowerCase())
      );
    }
    
    // 按时间倒序排序
    filteredData.sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime());
    
    // 分页
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedData = filteredData.slice(startIndex, endIndex);
    
    return {
      data: paginatedData,
      total: filteredData.length,
      success: true,
      message: '获取消息列表成功'
    };
  },

  async getMessageStats(): Promise<ApiResponse<MessageStats>> {
    await new Promise(resolve => setTimeout(resolve, 100));
    
    const stats = getMessageStats(messageData);
    
    return {
      data: stats,
      total: 1,
      success: true,
      message: '获取消息统计成功'
    };
  },

  async markAsRead(messageId: number): Promise<ApiResponse<Message>> {
    await new Promise(resolve => setTimeout(resolve, 100));
    
    const message = messageData.find(msg => msg.id === messageId);
    if (!message) {
      throw new Error('消息不存在');
    }
    
    message.read = true;
    
    return {
      data: message,
      total: 1,
      success: true,
      message: '消息已标记为已读'
    };
  },

  async markAsUnread(messageId: number): Promise<ApiResponse<Message>> {
    await new Promise(resolve => setTimeout(resolve, 100));
    
    const message = messageData.find(msg => msg.id === messageId);
    if (!message) {
      throw new Error('消息不存在');
    }
    
    message.read = false;
    
    return {
      data: message,
      total: 1,
      success: true,
      message: '消息已标记为未读'
    };
  },

  async markAllAsRead(): Promise<ApiResponse<boolean>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    messageData.forEach(message => {
      message.read = true;
    });
    
    return {
      data: true,
      total: 1,
      success: true,
      message: '所有消息已标记为已读'
    };
  },

  async deleteMessage(messageId: number): Promise<ApiResponse<boolean>> {
    await new Promise(resolve => setTimeout(resolve, 100));
    
    const index = messageData.findIndex(msg => msg.id === messageId);
    if (index === -1) {
      throw new Error('消息不存在');
    }
    
    messageData.splice(index, 1);
    
    return {
      data: true,
      total: 1,
      success: true,
      message: '消息删除成功'
    };
  },

  async deleteAllRead(): Promise<ApiResponse<boolean>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    for (let i = messageData.length - 1; i >= 0; i--) {
      if (messageData[i].read) {
        messageData.splice(i, 1);
      }
    }
    
    return {
      data: true,
      total: 1,
      success: true,
      message: '已删除所有已读消息'
    };
  },

  async batchOperation(request: BatchOperationRequest): Promise<ApiResponse<boolean>> {
    await new Promise(resolve => setTimeout(resolve, 300));
    
    const { messageIds, operation } = request;
    
    messageIds.forEach(messageId => {
      const message = messageData.find(msg => msg.id === messageId);
      if (message) {
        switch (operation) {
          case 'markAsRead':
            message.read = true;
            break;
          case 'markAsUnread':
            message.read = false;
            break;
          case 'delete':
            const index = messageData.findIndex(msg => msg.id === messageId);
            if (index !== -1) {
              messageData.splice(index, 1);
            }
            break;
        }
      }
    });
    
    return {
      data: true,
      total: messageIds.length,
      success: true,
      message: `批量操作成功，处理了${messageIds.length}条消息`
    };
  }
};

export const messageApi = {
  // 获取消息列表（支持分页、搜索、筛选）
  async getMessages(params: GetMessagesParams = {}): Promise<ApiResponse<Message[]>> {
    if (shouldUseMockServer()) {
      return mockMessageApi.getMessages(params);
    }
    
    try {
      const { page = 1, pageSize = 10, type, read, important, search } = params;
      
      // 构建查询参数
      const queryParams = new URLSearchParams({
        page: page.toString(),
        pageSize: pageSize.toString()
      });
      
      if (type) queryParams.append('type', type);
      if (read !== undefined) queryParams.append('read', read.toString());
      if (important !== undefined) queryParams.append('important', important.toString());
      if (search) queryParams.append('search', search);
      
      const url = `${MESSAGE_API_BASE}?${queryParams.toString()}`;
      
      // 发送GET请求
      const response = await http.get<BackendApiResponse<MessageListResponse>>(url);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        const messageList = backendData.data as MessageListResponse;
        return {
          data: messageList.messages || [],
          total: messageList.total || 0,
          success: true,
          message: backendData.message || '获取消息列表成功'
        };
      } else {
        throw new Error(backendData.message || '获取消息列表失败');
      }
    } catch (error) {
      console.error('获取消息列表失败:', error);
      throw error;
    }
  },

  // 获取消息统计
  async getMessageStats(): Promise<ApiResponse<MessageStats>> {
    if (shouldUseMockServer()) {
      return mockMessageApi.getMessageStats();
    }
    
    try {
      const url = `${MESSAGE_API_BASE}/stats`;
      const response = await http.get<BackendApiResponse<MessageStatsResponse>>(url);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        const statsResponse = backendData.data as MessageStatsResponse;
        return {
          data: statsResponse.stats,
          total: 1,
          success: true,
          message: backendData.message || '获取消息统计成功'
        };
      } else {
        throw new Error(backendData.message || '获取消息统计失败');
      }
    } catch (error) {
      console.error('获取消息统计失败:', error);
      throw error;
    }
  },

  // 标记消息为已读
  async markAsRead(messageId: number): Promise<ApiResponse<Message>> {
    if (shouldUseMockServer()) {
      return mockMessageApi.markAsRead(messageId);
    }
    
    try {
      const url = `${MESSAGE_API_BASE}/${messageId}/read`;
      const response = await http.put<BackendApiResponse<Message>>(url);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '消息已标记为已读'
        };
      } else {
        throw new Error(backendData.message || '标记消息为已读失败');
      }
    } catch (error) {
      console.error('标记消息为已读失败:', error);
      throw error;
    }
  },

  // 标记消息为未读
  async markAsUnread(messageId: number): Promise<ApiResponse<Message>> {
    if (shouldUseMockServer()) {
      return mockMessageApi.markAsUnread(messageId);
    }
    
    try {
      const url = `${MESSAGE_API_BASE}/${messageId}/unread`;
      const response = await http.put<BackendApiResponse<Message>>(url);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '消息已标记为未读'
        };
      } else {
        throw new Error(backendData.message || '标记消息为未读失败');
      }
    } catch (error) {
      console.error('标记消息为未读失败:', error);
      throw error;
    }
  },

  // 标记所有消息为已读
  async markAllAsRead(): Promise<ApiResponse<boolean>> {
    if (shouldUseMockServer()) {
      return mockMessageApi.markAllAsRead();
    }
    
    try {
      const url = `${MESSAGE_API_BASE}/read-all`;
      const response = await http.put<BackendApiResponse<boolean>>(url);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '所有消息已标记为已读'
        };
      } else {
        throw new Error(backendData.message || '标记所有消息为已读失败');
      }
    } catch (error) {
      console.error('标记所有消息为已读失败:', error);
      throw error;
    }
  },

  // 删除消息
  async deleteMessage(messageId: number): Promise<ApiResponse<boolean>> {
    if (shouldUseMockServer()) {
      return mockMessageApi.deleteMessage(messageId);
    }
    
    try {
      const url = `${MESSAGE_API_BASE}/${messageId}`;
      const response = await http.delete<BackendApiResponse<boolean>>(url);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '消息删除成功'
        };
      } else {
        throw new Error(backendData.message || '删除消息失败');
      }
    } catch (error) {
      console.error('删除消息失败:', error);
      throw error;
    }
  },

  // 删除所有已读消息
  async deleteAllRead(): Promise<ApiResponse<boolean>> {
    if (shouldUseMockServer()) {
      return mockMessageApi.deleteAllRead();
    }
    
    try {
      const url = `${MESSAGE_API_BASE}/delete-read`;
      const response = await http.delete<BackendApiResponse<boolean>>(url);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '已删除所有已读消息'
        };
      } else {
        throw new Error(backendData.message || '删除所有已读消息失败');
      }
    } catch (error) {
      console.error('删除所有已读消息失败:', error);
      throw error;
    }
  },

  // 批量操作
  async batchOperation(request: BatchOperationRequest): Promise<ApiResponse<boolean>> {
    if (shouldUseMockServer()) {
      return mockMessageApi.batchOperation(request);
    }
    
    try {
      const url = `${MESSAGE_API_BASE}/batch`;
      const response = await http.post<BackendApiResponse<boolean>>(url, request);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: request.messageIds.length,
          success: true,
          message: backendData.message || '批量操作成功'
        };
      } else {
        throw new Error(backendData.message || '批量操作失败');
      }
    } catch (error) {
      console.error('批量操作失败:', error);
      throw error;
    }
  }
};